# -*- coding: utf-8 -*-
import json
import logging

from flask import request, g
from werkzeug.exceptions import HTTPException
from app import create_app
from app.libs.error import APIException
from app.libs.error_code import ServerError
from gevent import monkey

# monkey.patch_all()
app = create_app()
# gunicorn_logger = logging.getLogger('gunicorn.error')
# app.logger.handlers = gunicorn_logger.handlers
# app.logger.setLevel(gunicorn_logger.level)


@app.errorhandler(Exception)
def framework_error(e):
    if isinstance(e, APIException):
        return e
    if isinstance(e, HTTPException):
        code = e.code
        msg = e.description
        error_code = 1007
        return APIException(msg, code, error_code)
    else:
        # 调试模式
        # log
        if not app.config['DEBUG']:
            message = '[%s] -> [%s] from:%s costs:%.3f ms' % (
                request.method,
                request.path,
                request.remote_addr,
                float(g.request_time()) * 1000
            )
            req_body = '{}'
            try:
                req_body = request.get_json() if request.get_json() else {}
            except:
                pass
            message += " data:{\n\tparam: %s, \n\tbody: %s\n} \n错误信息: %s" % (
                json.dumps(request.args, ensure_ascii=False),
                req_body,
                e
            )
            app.logger.error(message)
            app.logger.error(e)
            return ServerError()
        else:
            raise e


if __name__ == '__main__':
    # from gevent import pywsgi
    # from geventwebsocket.handler import WebSocketHandler
    # app.debug = False
    # server = pywsgi.WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
    # server.serve_forever()
    # app.run()
    app.run(host='0.0.0.0', port=5009, debug=True)
